package com.zyf.project.capchain.interceptor;

import com.zyf.project.capchain.utils.common.JwtUtils;
import com.zyf.project.capchain.exceptions.TokenException;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.MalformedJwtException;
import io.jsonwebtoken.SignatureException;
import org.jetbrains.annotations.NotNull;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author Zhou Yifan
 */
@Component
public class JwtInterceptor implements HandlerInterceptor {

    @Resource
    JwtUtils jwtUtils;

    @Override
    public boolean preHandle(@NotNull HttpServletRequest request, @NotNull HttpServletResponse response, @NotNull Object handler){

        //获取请求头token
        String token = request.getHeader("Authorization");

        try{
            //校验token
            jwtUtils.verifyToken(token);
            //放行请求
            return true;
        }catch (ExpiredJwtException e){
            e.printStackTrace();
            throw new TokenException("token过期！");
        }catch (MalformedJwtException e){
            e.printStackTrace();
            throw new TokenException("token格式错误！");
        }catch (SignatureException e){
            e.printStackTrace();
            throw new TokenException("无效签名！");
        }catch (IllegalArgumentException e){
            e.printStackTrace();
            throw new TokenException("非法请求！");
        }catch (Exception e){
            e.printStackTrace();
            throw new TokenException("token无效！");
        }
    }
}
